import 'package:flutter/cupertino.dart';
import 'package:flutter_09_game/base/controller/base_controller.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/http/http_export.dart';
import 'package:flutter_09_game/http/http_manager.dart';
import 'package:flutter_09_game/pages/promotion/models/model_wallet_config.dart';
import 'package:flutter_09_game/user/app_user_manager.dart';
import 'package:flutter_09_game/user/model/model_user_wallet.dart';
import 'package:flutter_09_game/utils/extensions/num_ext.dart';
import 'package:flutter_09_game/utils/loading/loading_utils.dart';
import 'package:flutter_09_game/utils/log/utils_log.dart';
import 'package:flutter_09_game/widgets/verify_input_box/src/verification_box.dart';
import 'package:get/get.dart';

class PromotionWithdrawLogic extends BaseController {
// List<String> options = ['USDT', "TRX"];
  List<String> options =
      AppUserManager().walletList.map((item) => item.symbol ?? '').toList();

  late var selectorTagRx = ''.obs;

  ModelUserWallet? currentWallet;

  TextEditingController editingController = TextEditingController();

  VerificationBoxController verificationBoxController =
      VerificationBoxController();
  RxString fundPassword = ''.obs;

  RxBool isFormValid = false.obs;

  Rx<ModelWalletConfig> walletConfigRx = Rx(ModelWalletConfig());

  Map<String, ModelPromotionDropdown> _dropdownMap = {};

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    getWalletData();
    getSettingWithdrawConfig();

    ever(fundPassword, (val) {
      validateForm();
    });

    ever(selectorTagRx, (val) {
      currentWallet = AppUserManager()
          .walletList
          .firstWhereOrNull((item) => item.symbol == selectorTagRx.value);
      update();
    });
  }

  Future getWalletData() async {
    if (AppUserManager().walletList.isEmpty) {
      await AppUserManager().loadWalletData();
    }
    if (AppUserManager().walletList.isEmpty) {
      // Get.back();
    } else {
      // clog('dasldkaskl;d');
      currentWallet = AppUserManager().walletList.firstWhereOrNull(
              (item) => item.symbol?.toUpperCase() == "RTX") ??
          AppUserManager().walletList.first;
      selectorTagRx.value = currentWallet?.symbol ?? '';
      update();
    }
  }

  void validateForm() {
    // clog('asldjaslk');
    final isValid = editingController.text.trim().isNotEmpty &&
        fundPassword.value.length == 6;
    isFormValid.value = isValid;
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
    editingController.dispose();
  }

  postWithdraw() async {
    if ((double.tryParse(editingController.text) ?? 0) * 1000000 <
        (selectorTagRx.value == 'TRX'
            ? (walletConfigRx.value.config?.withdrawLimitForTrx?.minAmount ?? 0)
            : (walletConfigRx.value.config?.withdrawLimitForUsdt?.minAmount ??
                0))) {
      LoadingUtils.showToast(LocaleKeys.withdrawAmountLimit.tr.trArgs([
        "${selectorTagRx.value == 'TRX' ? (walletConfigRx.value.config?.withdrawLimitForTrx?.minAmount ?? 0).formatLimiting() : (walletConfigRx.value.config?.withdrawLimitForUsdt?.minAmount ?? 0).formatLimiting()} ${selectorTagRx.value.toUpperCase()}"
      ]));
      return;
    }
    if ((double.tryParse(editingController.text) ?? 0) * 1000000 >
        (selectorTagRx.value == 'TRX'
            ? (walletConfigRx.value.config?.withdrawLimitForTrx?.maxAmount ?? 0)
            : (walletConfigRx.value.config?.withdrawLimitForUsdt?.maxAmount ??
                0))) {
      LoadingUtils.showToast(LocaleKeys.withdrawAmountMaxLimit.tr.trArgs([
        "${selectorTagRx.value == 'TRX' ? (walletConfigRx.value.config?.withdrawLimitForTrx?.maxAmount ?? 0).formatLimiting() : (walletConfigRx.value.config?.withdrawLimitForUsdt?.maxAmount ?? 0).formatLimiting()} ${selectorTagRx.value.toUpperCase()}"
      ]));
      return;
    }

    if ((walletConfigRx.value.times ?? 0) >
        (walletConfigRx.value.config?.withdrawTimesPerDay ?? 0)) {
      LoadingUtils.showToast(LocaleKeys.withdrawTimesExceed.tr);
      return;
    }

    HttpResponse response = await HttpManager().post(
      API.postWithdraw,
      // fromJson: .fromJson,
      params: {
        'amount': (int.tryParse(editingController.text) ?? 0) * 1000000,
        'fund_password': fundPassword.value,
        'symbol': selectorTagRx.value.toUpperCase(),
        'type': getSelectDrop()?.tag?.startsWith('1') == true ? 1 : 2
      },
    );
    if (response.isSuccess) {
      LoadingUtils.showToast(LocaleKeys.submitSuccess.tr);
      await AppUserManager().loadWalletData();
      currentWallet = AppUserManager()
          .walletList
          .firstWhereOrNull((item) => item.symbol == selectorTagRx.value);
      update();
      walletConfigRx.value.times = (walletConfigRx.value.times ?? 0) + 1;

      editingController.text = '';
      verificationBoxController.text = '';
      fundPassword.value = '';
    }
  }

  getSettingWithdrawConfig() async {
    // getSettingWithdrawConfig
    HttpResponse response = await HttpManager().get(
      API.getSettingWithdrawConfig,
      fromJson: ModelWalletConfig.fromJson,
    );
    if (response.isSuccess) {
      walletConfigRx.value = response.data;
      // clog(' walletConfigRx.value   ${ walletConfigRx.value.times}');
    }
  }

  List<ModelPromotionDropdown> getDropdownDatas() {
    ModelUserWallet? wallet = AppUserManager()
        .walletList
        .firstWhereOrNull((item) => item.symbol == selectorTagRx.value);

    if (wallet != null) {
      List<ModelPromotionDropdown> items = [
        ModelPromotionDropdown(
            title: LocaleKeys.balance.tr,
            balance: wallet.balance,
            symbol: wallet.symbol,
            tag: '1+${wallet.symbol}'),
        ModelPromotionDropdown(
            title: LocaleKeys.commission.tr,
            balance: wallet.rebateBalance,
            symbol: wallet.symbol,
            tag: '2+${wallet.symbol}')
      ];

      if (!_dropdownMap.keys.contains(wallet.symbol)) {
        _dropdownMap[wallet.symbol ?? ""] = items.first;
      }

      return items;
    }

    return [];
  }

  updateSelectDrop(ModelPromotionDropdown? model) {
    if (model != null) {
      _dropdownMap[selectorTagRx.value] = model;
      update();
    }
  }

  ModelPromotionDropdown? getSelectDrop() {
    return _dropdownMap[selectorTagRx.value];
  }
}

class ModelPromotionDropdown {
  String? title;
  int? balance;
  String? symbol;
  String? tag;

  ModelPromotionDropdown({
    this.tag,
    this.title,
    this.balance,
    this.symbol,
  });

  ModelPromotionDropdown.fromJson(Map<String, dynamic> json) {
    balance = json['balance']?.toInt();
    tag = json['tag']?.toString();
    title = json['title']?.toString();
    symbol = json['symbol']?.toString();
  }

  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};
    data['balance'] = balance;
    data['title'] = title;
    data['symbol'] = symbol;
    data['tag'] = tag;
    return data;
  }
}

class ModelHomeDropdown {
  int? balance;
  String? symbol;

  ModelHomeDropdown({
    this.balance,
    this.symbol,
  });

  ModelHomeDropdown.fromJson(Map<String, dynamic> json) {
    balance = json['balance']?.toInt();

    symbol = json['symbol']?.toString();
  }

  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};
    data['balance'] = balance;
    data['symbol'] = symbol;
    return data;
  }
}
